<template>
	<div class="pictureManage" v-loading="loadingBox">
		<div class="pictureManage-right">
			<div class="pictureManage-right-button">
				<div class="children-search">
					<el-input style="margin-left: 30px;" v-model="searchInput" placeholder="请输入内容"></el-input>
					<el-button size="small" icon="el-icon-search" @click="searchList">搜索</el-button>
					<el-button size="small" type="primary" @click="selectSearchMl">选择查询目录</el-button>
				</div>
				<div class="children-search">
					<el-button size="small" type="primary" @click="generateWord">生成word</el-button>
				</div>
			</div>
			<div class="pictureManage-right-table">
				<el-table
						v-loading="loading"
						@selection-change="changeFun"
						:data="fileTableData"
						height="93%"
						border
						style="width: 100%;">
					<el-table-column
							align="center"
							type="selection"
							width="60">
					</el-table-column>
					<el-table-column
							align="center"
							label="文件名">
						<template slot-scope="scope">
							<div @click.stop="lookFileFlooer(scope.row)" style="cursor: pointer;width: 100%;display: flex;justify-content: flex-start;align-items: center;">
								<img v-if="scope.row.type==0" src="../../public/image/icon_wenjian.svg"/>
								<img v-else-if="scope.row.type==1" src="../../public/image/icon_photo.svg"/>
								<span style="margin-left: 15px;" v-text="scope.row.name"></span>
							</div>
						</template>
					</el-table-column>
					<el-table-column
							align="center"
							label="文件位置">
						<template slot-scope="scope">
							<span @click="openFileFloader(scope.row)" style="cursor: pointer;color: #66b1ff;" v-if="scope.row.type==1" v-text="scope.row.url"></span>
						</template>
					</el-table-column>
					<el-table-column
							align="center"
							label="文件大小">
						<template slot-scope="scope">
							<span v-if="scope.row.type==1">{{scope.row.size | fileSizeZh}}</span>
						</template>
					</el-table-column>
					<el-table-column
							align="center"
							prop="createTime"
							label="文件创建时间">
					</el-table-column>
					<!--<el-table-column-->
					<!--align="center"-->
					<!--width="120"-->
					<!--label="操作">-->
					<!--<template slot-scope="scope">-->
					<!--<el-button-->
					<!--type="danger"-->
					<!--size="mini"-->
					<!--@click="handleDelete(scope.$index, scope.row)">删除-->
					<!--</el-button>-->
					<!--</template>-->
					<!--</el-table-column>-->
				</el-table>
			</div>
		</div>

		<!--弹出层-->
		<el-drawer
				title="文件目录"
				:append-to-body="true"
				custom-class="xzmltcc"
				:visible.sync="drawer"
				direction="rtl"
				:modal-append-to-body="false"
				:show-close="false"
				size="46%">
			<div class="mulucaidan">
				<el-tree
						:data="treeData"
						show-checkbox
						default-expand-all
						node-key="id"
						ref="tree"
						highlight-current
						@check="checkTreeNode"
						:props="defaultProps">
				</el-tree>
			</div>
		</el-drawer>

		<!--图片预览-->
		<el-dialog title="图片预览" :visible.sync="imgYulan">
			<div style="display: flex;justify-content: center;width: 100%;">
				<img style="max-width: 100%;max-height: 300px;" :src="imgYulanUrl" />
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click="imgYulan = false">取 消</el-button>
				<el-button size="mini" type="primary" @click="imgYulan = false">确 定</el-button>
			</div>
		</el-dialog>

		<!--word文件名称-->
		<el-dialog title="word文件名" :visible.sync="addFileFloorVisible">
			<div>
				<el-input v-model="fileNameInput" placeholder="请输入要生成的word文件名"></el-input>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click="addFileFloorVisible = false">取 消</el-button>
				<el-button size="mini" type="primary" @click="primaryFileNmae">确 定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
    import { PicInfoService } from '@/util/sqlite/service/PicInfoService';
    import { MenuInfoService } from '@/util/sqlite/service/MenuInfoService';

    var fs = require('fs');

    /*文件*/
    var picInfoService = new PicInfoService();
    var serv = picInfoService.constructor.prototype;

    const { Document, Footer, Header, Packer, Paragraph,TableOfContents, StyleLevel, HeadingLevel,Media } = docx;

    import '@/util/docx/index';

    export default {
        data() {
            return {
                sizeImage:[],

                //全局loading
                loadingBox: false,

                //要生成的word文件名称
                addFileFloorVisible: false,
                fileNameInput: "",

                //弹出框
                drawer: false,
                //树形菜单
                treeData: [],
                checkedKeys: [],
                defaultProps: {
                    children: 'children',
                    label: 'menu_name'
                },

                //图片预览
                imgYulan: false,
                imgYulanUrl: "",

                loading: false,
                multipleSelection: [],

                //表格文件
                fileTableData: [],

                //菜单id
                menuId: 0,//第一级为0

                searchInput: "",

				doc: null
            }
        },
        filters: {
            fileSizeZh(size){
                var data = "";
                if (size < 0.1 * 1024) { //如果小于0.1KB转化成B
                    data = size.toFixed(1) + "B";
                } else if (size < 0.1 * 1024 * 1024) {//如果小于0.1MB转化成KB
                    data = (size / 1024).toFixed(1) + "KB";
                } else if (size < 0.1 * 1024 * 1024 * 1024) { //如果小于0.1GB转化成MB
                    data = (size / (1024 * 1024)).toFixed(1) + "MB";
                } else { //其他转化成GB
                    data = (size / (1024 * 1024 * 1024)).toFixed(1) + "GB";
                }
                var sizestr = data + "";
                var len = sizestr.indexOf("\.");
                var dec = sizestr.substr(len + 1, 2);
                if (dec == "00") {//当小数点后为00时 去掉小数部分
                    return sizestr.substring(0, len) + sizestr.substr(len + 3, 2);
                }
                return sizestr;
            }
        },
        mounted() {
            let self = this;
            //获取所有的目录
            self.getAllFileFloor();
        },
        methods: {
            //选择查询目录
            selectSearchMl(){
                let self=this;
                self.drawer = true;
            },
            //查询所有目录
            getAllFileFloor(){
                let self = this;
                setTimeout(()=>{
                    var obj = {
                    };
                    var res = serv.getAllMenu(obj);
                    if(res.code==200){
                        res.data.then((data)=>{
                            //得到分好级别的目录
                            self.getMenuTreeData(data);
                        });
                    }
                },300);
            },
            //先得到第一级目录
            getMenuTreeData (json_data) {
                var _this = this;
                var menuJsonData = [];// 菜单数组
                var parentList = [];// 所有一级菜单数组
                for (var i = 0; i < json_data.length; i++) {
                    var obj = {};
                    obj["children"] = [];//给每个菜单对象增加一个children属性
                    obj["id"] = json_data[i].id;
                    obj["parent_id"] = json_data[i].parent_id;
                    obj["menu_name"] = json_data[i].menu_name;
                    menuJsonData.push(obj);
                    if (json_data[i].parent_id == 0) {
                        parentList.push(obj);
                    }
                }
                for (var i = 0; i < parentList.length; i++) {
                    parentList[i] = _this.recuTree(parentList[i], menuJsonData);
                }

                _this.treeData = parentList;
            },
            recuTree (parentMenu, menuJsonData) {
                var _this = this;
                for (var i = 0; i < menuJsonData.length; i++) {
                    if (parentMenu.id == menuJsonData[i].parent_id) {
                        menuJsonData[i] = _this.recuTree(menuJsonData[i], menuJsonData);
                        parentMenu["children"].push(menuJsonData[i]);
                    }
                }

                return parentMenu;
            },
            //选中节点
            checkTreeNode(checkedNodes,checkedKeys,halfCheckedNodes,halfCheckedKeys){
                let self = this;
                self.checkedKeys = checkedKeys.checkedKeys;
            },

            //生成word
            async generateWord(){
                let self = this;
                if(self.multipleSelection.length<=0){
                    self.$message({
                        message:"请先选择要生成word的图片!",
                        type:"warning",
                    });
                    return;
                }
                self.addFileFloorVisible = true;
            },
            //循环得到图片添加如doc中的数据
            getImgs(){
                let self = this;
                let imageArray = [];
                self.multipleSelection.forEach(async (items,index)=>{
                    let getImg = await Media.addImage(self.doc,fs.readFileSync(items.url),self.sizeImage[index][0],self.sizeImage[index][1]);
                    imageArray.push(getImg);
                });
                return imageArray;
            },
            //将docImportImg插入到doc文档中
            async getDocImportImgEnd(docImportImg){
                let self = this;
                let Paragraphs = [];
                docImportImg.forEach((items,index)=>{
                    Paragraphs.push(new Paragraph(items));
                    Paragraphs.push(new Paragraph({
                        text: self.splitImg(self.multipleSelection[index].name),
                        heading: HeadingLevel.HEADING_1
                    }));
                });
                await self.doc.addSection({
                    children: Paragraphs
                });
            },
            //截取后缀名为.gif,.jpg,.jpeg,.png,.GIF,.JPG,.PNG的图片
            splitImg(imgName){
                return imgName.substring(0,imgName.indexOf("."));
            },

            //图片生成word操作逻辑
            async primaryFileNmae(){
                let self = this;
                const sizeOf = require('image-size');
                self.sizeImage = [];
                self.multipleSelection.forEach((items,index)=>{
                    let dimensions = sizeOf(items.url);
                    self.sizeImage.push([dimensions.width, dimensions.height]);
                });
                if(self.$store.getters.getSaveCatalogWord==""){
                    self.$message({
                        message:"请选择word文档要存储的目录",
                        type: "warning"
                    });
                    return;
                }
                var isexist = fs.existsSync( self.$store.getters.getSaveCatalogWord );
                if(!isexist){
                    self.$message({
                        message:"不存在word文档存储目录，请更换系统目录",
                        type:"error"
                    });
                    return;
                }
                self.loadingBox = true;

                //定义doc
                self.doc = new docx.Document();
                //得到图片添加如doc中的数据
				let docImportImg = await self.getImgs();
				//将docImportImg插入到doc文档中
				await self.getDocImportImgEnd(docImportImg);
				await Packer.toBuffer(self.doc).then((buffer)=>{
					fs.writeFileSync(self.$store.getters.getSaveCatalogWord+"\\"+self.fileNameInput+'_'+self.getTime(new Date())+'.docx',buffer);
				});
				self.loadingBox = false;
				self.$message({
					message:"word生成成功!",
					type:"success",
				});
				self.addFileFloorVisible = false;
            },

            //获取当前时间的  2019-09-08 00：00：00
            getTime(timestamp){
                let self = this;
                var d = new Date(timestamp);
                return d.getFullYear() + '' + ((d.getMonth() + 1)<10?'0'+(d.getMonth() + 1):(d.getMonth() + 1)) + '' + (d.getDate()<10?'0'+d.getDate():d.getDate()) + '' + (d.getHours()<10?'0'+d.getHours():d.getHours()) + '' + (d.getMinutes()<10?'0'+d.getMinutes():d.getMinutes()) + '' + (d.getSeconds()<10?'0'+d.getSeconds():d.getSeconds());
            },

            //查看图片
            openFileFloader(items){
                let self=this;
                let dir = items.url;
                fs.exists(dir, function(bool){
                    if(bool){
                        const { shell } = require("electron").remote;
                        shell.showItemInFolder(dir);
                    }else{
                        self.$message({
                            message:"未找到项目文件!",
                            type:"warning",
                        })
                    }
                });
            },

            //选中表格数据
            changeFun(val) {
                let self = this;
                self.multipleSelection = val;
            },

            //查看某张图片
            lookFileFlooer(row){
                let self = this;
                var fs = require("fs");
                var imageData = fs.readFileSync(row.url);
                var imageBase64 = imageData.toString("base64");
                var imagePrefix = "data:image/bmp;base64,";

                self.imgYulan = true;
                self.$nextTick(()=>{
                    self.imgYulanUrl = imagePrefix + imageBase64;
                })
            },

            //搜索查询图片
            searchList(){
                let self = this;
                self.getAllFile();
            },
            //根据菜单id以及关键字模糊查询图片
            getAllFile(){
                let self = this;
                self.loading = true;
                setTimeout(()=>{
                    var obj = {
                        id: JSON.parse(JSON.stringify(self.checkedKeys)).join(","),
                        queryName: self.searchInput,
                        catalog: self.$store.getters.getSaveCatalog
                    };
                    var res = serv.getAllPic(obj);
                    if(res.code==200){
                        res.data.then((data)=>{
                            self.fileTableData = data;
                        });
                    }
                    self.loading = false;
                },300);
            },

            //时间格式化
            changeTime(d) {
                let self = this;
                var datetime = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds();
                return datetime;
            }
        }
    }
</script>

<style scoped lang="scss">
	.mulucaidan {
		padding: 0 20px 20px;
	}

	/deep/ .xzmltcc {
		border-top: 1px solid rgba(0,0,0,0.3);
	}

	/deep/ .el-breadcrumb__inner>span {
		cursor: pointer;
	}

	/deep/ .upload-box .el-dialog__body {
		max-height: 200px;
		overflow: auto;
	}

	/deep/ .avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		width: 150px;
		height: 150px;
	}

	/deep/ .upload-demo .el-upload--text {
		text-align: left !important;
	}

	/deep/ .avatar-uploader-icon {
		width: 150px !important;
		height: 150px !important;
		line-height: 150px !important;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.pictureManage {
		font-size: 18px;
		font-style: normal;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
		position: relative;
		width: 100%;
		height: 100%;
		overflow: hidden;
		padding: 20px 30px;
		background: #F4F4F4;
		box-sizing: border-box;

		.pictureManage-left {
			width: 260px;
			height: 100%;
			background: #F4F4F4;

			.pictureManage-left-title {
				width: 100%;
				font-size: 24px;
				font-family: "webfontM";
				box-sizing: border-box;
				padding: 20px;
			}
		}

		.pictureManage-right {
			position: relative;
			/*position: absolute;*/
			/*top: 0;*/
			/*left: 0px;*/
			/*right: 0;*/
			/*bottom: 0;*/
			width: 100%;
			height: 100%;
			background: #ffffff;
			border-radius: 8px;

			.pictureManage-right-button {
				width: 100%;
				height: 73px;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: 1px solid #DCDFE6;
				box-sizing: border-box;

				button {
					margin-left: 20px;
				}

				.children-search {
					padding-right: 20px;
					display: flex;
					justify-content: flex-start;
					align-items: center;
				}
			}

			.pictureManage-right-table {
				position: absolute;
				top: 100px;
				left: 0;
				right: 0;
				bottom: 0;
				overflow: hidden;
				padding: 20px;
			}
		}
	}
</style>
